package com.llsydn.a01androidh5;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

/**
 * @author lilinshen
 * @title Java代码和H5代码互调
 * @description js调用java，播放视频
 * @date 2018/10/19 14:38
 */
public class JsJavaVideoActivity extends Activity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_java);
        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        //设置支持js代码
        webSettings.setJavaScriptEnabled(true);
        //不调起浏览器-自定义浏览器
        webView.setWebViewClient(new WebViewClient());

        //添加JavascriptInterface
        //以后js通过android字段，调用JavascriptInterface的任何方法。例如：window.Android.xxxx
        webView.addJavascriptInterface(new AndroidAndJsInterface(), "android");

        //加载网页（网络或本地的）
        //webView.loadUrl("http://www.zhongshanou.cn/ddmh/portal/home/index.jhtml");
        webView.loadUrl("file:///android_asset/RealNetJSCallJavaActivity.htm");
    }

    /**
     * js调java
     */
    class AndroidAndJsInterface {
        /**
         * 将会被js调用
         */
        @JavascriptInterface
        public void playVideo(int id, String videoUrl, String title) {
            Toast.makeText(JsJavaVideoActivity.this, id + videoUrl + title, Toast.LENGTH_SHORT).show();

            //把所有的播放器调起来，并播放
            Intent intent = new Intent();
            intent.setDataAndType(Uri.parse(videoUrl), "video/*");
            startActivity(intent);
        }
    }
}
